﻿namespace LiteBlog.Components
{
    using System.Web;
    using LiteBlog.Common.Entities;
    using LiteBlog.Common.Components;
    using LiteBlog.Repositories.Contracts;
    using LiteBlog.Components.Contracts;

    public class StatComp : BaseComp<IStatRepository>, IStatComp
    {
        
        public StatComp(IStatRepository data, ICacheComp cache) : base(data, cache) { }

        // Save stuff to application instead of cache
        // forgot why? - Most likely, because the cache uses ASP.NET cache
        // Cache is not available at the time of saving in Application end

        // abstract the location of Stat in Application object!
        // except for the saving part! which will be done in application end!

        
        public void IncrementFeeds()
        {
            Stat stat = (Stat)HttpContext.Current.Application["Stat"];
            string feedKey = Stat.GetFeedKey(DateTimeHelper.Now);
            stat.Feeds[feedKey] = stat.Feeds.ContainsKey(feedKey) ? stat.Feeds[feedKey] + 1 : 1;
            HttpContext.Current.Application["Stat"] = stat;
        }

        public void IncrementHits()
        {
            Stat stat = (Stat)HttpContext.Current.Application["Stat"];
            stat.Hits++;
            stat.ViewsThisMonth++;
            HttpContext.Current.Application["Stat"] = stat;
        }


        public void IncrementPosts(string fileId)
        {
            Stat stat = (Stat)HttpContext.Current.Application["Stat"];
            if (stat.PageVisits.ContainsKey(fileId))
                stat.PageVisits[fileId].Views = stat.PageVisits[fileId].Views + 1;
            HttpContext.Current.Application["Stat"] = stat;
        }

        public void IncrementVisits()
        {
            Stat stat = (Stat)HttpContext.Current.Application["Stat"];
            stat.Visits = stat.Visits + 1;
            HttpContext.Current.Application["Stat"] = stat;
        }

        public Stat Load()
        {
            var stat = (Stat)HttpContext.Current.Application["Stat"];
            if (stat == null)
            {
                stat = _data.Load();
                HttpContext.Current.Application["Stat"] = stat;
            }
            return stat;
        }

        public void Save(Stat stat)
        {
            if(stat!=null)
                _data.Save(stat);
        }
    }
}